<?php

namespace App\Modules\Admin\Entities\Equipment;

use App\Models\Model;
use App\Modules\Admin\Entities\Water\WaterDeviceModel;
use Illuminate\Support\Facades\Cache;

class EquipmentParamsFreeModel extends Model
{
    protected $table='equipment_params_free';
    protected $primaryKey='id';
    protected $is_delete=0;

    // 缓存 key
    protected $cache_key  = 'water:device:equipment_params';

    public function water_device_info(){
        return $this->hasOne(WaterDeviceModel::class,'water_id','water_id')->select(['water_id','water_title']);
    }



    public function getFreeByid($fee_id)
    {
       return $this->where(['id'=>$fee_id,'is_delete'=>0])->first();
    }
    public function getApparatusIdByType($apparatus_id,$type)
    {
       return $this->where(['water_id'=>$apparatus_id,'ttype'=>$type,'is_delete'=>0])->first();
    }
    public function getWaterDeviceIdByType($apparatus_id,$type)
    {
       return $this->where(['water_id'=>$apparatus_id,'ttype'=>$type,'is_delete'=>0])->first(['id','water_id','ttype','equipment_id','title','water_title','money']);
    }

    /**
     * 设备参数 缓存
     * @date 2025-04-29
     *  设备参数 缓存
     * @return array
     */
    public function getEquipmentParamsFreeCache($type=true)
    {
        $EquipmentParamsList = $this->where(['is_delete'=>0])->get(['id','water_id','ttype','equipment_id','title','water_title','money'])->toArray();
        $tree_cache=[];
        Cache::delete($this->cache_key);
        if ($type) {
            if (!Cache::has('water:device:job_cache')) {
                WaterDeviceModel::getInstance()->getCache();
            }
        }
        foreach ($EquipmentParamsList as $item){
            $equipment_id = $item['equipment_id'];
            $water_info = Cache::get('water:device:job_cache:eq_all:'.$equipment_id);
            $params_id = $item['id'];
            $water_id = $item['water_id'];
            $ttype = $item['ttype'];
            $item['water_title'] = $water_info['water_title'].'-'.$item['title'];
            $tree_cache['water'][$water_id][$ttype]=$item;
            $tree_cache['free'][$params_id]=$item;
            Cache::set($this->cache_key.':water:'.$water_id.':'.$ttype,$item);
            Cache::set($this->cache_key.':free:'.$params_id,$item);
        }
        return $tree_cache;
    }

}
